from urllib import request

from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.db.models import F
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from commodity.models import Types, CommodityInfos



def commodityView(request):
    title = '商品列表'
    classContent = 'commoditys'
    firsts = Types.objects.values('firsts').distinct()
    typesList = Types.objects.all()
    t = request.GET.get('t', '')
    s = request.GET.get('s', 'sold')
    p = request.GET.get('p', '1')
    n = request.GET.get('n', '')

    commodityInfos = CommodityInfos.objects.all()
    if t:
        types = Types.objects.filter(id=t).first()
        commodityInfos = commodityInfos.filter(types=types.seconds)
    if s:
        commodityInfos = commodityInfos.order_by('-' + s)
    if n:
        commodityInfos = commodityInfos.filter(name__contains=n)

    paginator = Paginator(commodityInfos, 6)
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)

    return render(request, 'commodity.html', locals())

def detailView(request, id):
    title = '商品介绍'
    classContent = 'details'
    items = CommodityInfos.objects.exclude(id=id).order_by('-sold')[:5]
    commoditys = CommodityInfos.objects.filter(id=id).first()
    likesList = request.session.get('likes', [])
    likes = True if id in likesList else False

    return render(request, 'details.html', locals())

def collectView(request):
    id = request.GET.get('id', '')
    result = {"result": '已收藏'}
    likes = request.session.get('likes', [])
    if id and not int(id) in likes:
        CommodityInfos.objects.filter(id=id).update(likes=F('likes') + 1)
        result["result"]="收藏成功"
        request.session['likes'] = likes+[int(id)]
    return JsonResponse(result)